<template>
  <div class="main package-container">
    <section v-loading="pageLoading">
      <el-form class="section-content" :rules="formRules" :model="formData" size="medium" ref="form" label-width="150px">
        <el-form-item label="组合名称：" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="组合副标题：" prop="subTitle">
          <el-input v-model="formData.subTitle"></el-input>
        </el-form-item>
        <el-form-item label="组合商品：" prop="relationList">
          <el-button type="primary" plain @click="chooseGoodsPackage" style="margin-bottom: 10px">选择商品</el-button>
          <el-table :data="formData.relationList" v-if="formData.relationList.length" border>
            <el-table-column align="center" label="套餐ID" prop="packageId" min-width="100"></el-table-column>
            <el-table-column align="center" label="套餐名称" prop="name" min-width="100"></el-table-column>
            <el-table-column align="center" label="套餐价格" prop="price" min-width="100"></el-table-column>
            <el-table-column align="center" label="是否售卖" width="120">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isSell"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="是"
                  inactive-text="否"
                  :active-value="1"
                  :inactive-value="0">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" min-width="100">
              <template slot-scope="scope">
                <el-button type="primary" @click="del(scope.row, scope.$index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <!--<el-form-item label="用户限购数量：" prop="userQuantity" subTitle :rules="commonRules.numberRuleZero">-->
          <!--<el-input v-model="formData.userQuantity"></el-input>-->
        <!--</el-form-item>-->

        <el-form-item label="组合主图：" prop="image" :rules="commonRules.notNullRule">
          <el-upload
            class="avatar-uploader"
            accept="image/*"
            :action="upladUrl"
            name="file"
            :show-file-list="false"
            :on-success="ImgSuccess"
            :before-upload="beforeUpload">
            <img v-if="formData.image" :src="formData.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="组合图片：" prop="imageList" :rules="commonRules.notNullRule">
          <ul class="upload-img-list">
            <draggable v-model="formData.imageList" :options="{group:'imageList'}" @start="drag=true" @end="drag=false">
              <li class="img-preview" v-for="(imgItem, imgIndex) of formData.imageList" :key="imgIndex">
                <img v-if="videoJudge(imgItem)" :src="imgItem" alt="" />
                <video v-else-if="!videoJudge(imgItem)" autoplay="autoplay" loop="loop">
                  <source :src="imgItem" type="video/mp4" >
                  您的浏览器不支持HTML5 Video
                </video>
                <div class="img-preview-mask">
                  <div class="mask-btn">
                    <i title="删除" class="el-icon-delete" @click="()=>{formData.imageList.splice(imgIndex, 1)}"></i>
                  </div>
                </div>
              </li>
            </draggable>
            <li>
              <label class="upload-btn">
                <input type="file" @change="(event)=>{uploadImg(event)}" />
                <i class="el-icon-plus"></i>
              </label>
            </li>
          </ul>
          <div v-if="formData.imageList.length>1" style="color: red">拖拽已上传的图片可以进行排序</div>
        </el-form-item>

        <el-form-item label="组合说明：" prop="remarks" :rules="commonRules.notNullRule">
          <el-input type="textarea" v-model="formData.remarks" maxLength="300"></el-input>
        </el-form-item>
        <el-form-item label="组合故事：" prop="story" :rules="commonRules.notNullRule">
          <el-input type="textarea" v-model="formData.story"></el-input>
        </el-form-item>
        <el-form-item label="组合详情：" prop="intro" :rules="commonRules.notNullRule">
          <tinymce :height="520" v-model="formData.intro"></tinymce>
        </el-form-item>
        <el-form-item label="已购人数：" prop="soldNumber" :rules="commonRules.numberRuleZero">
          <el-input v-model="formData.soldNumber"></el-input>
        </el-form-item>

        <!--<el-form-item label="组合标签：" prop="tagList">-->
          <!--<el-checkbox-group v-model="tempTagCheck" @change="changeTagArr">-->
            <!--<el-checkbox-->
              <!--v-for="item in tags"-->
              <!--:key="item.id"-->
              <!--:label="item.id"-->
            <!--&gt;{{item.name}}</el-checkbox>-->
          <!--</el-checkbox-group>-->
        <!--</el-form-item>-->
        <el-form-item label="是否允许被搜索">
          <el-switch
            v-model="formData.isSearched"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="是"
            inactive-text="否"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item v-if="!pageType">
          <el-button type="success" :loading="btnLoading" @click="save">保存</el-button>
        </el-form-item>

      </el-form>
    </section>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { getTagList } from '@/api/common'
import Tinymce from '@/components/Tinymce'
export default {
  name: "combinationEdit",
  props: {
    id: {
      default: ''
    }
  },
  components: {
    Tinymce,
    draggable
  },
  data() {
    const validPackageGoodsList = (rule, value, callback) => {
      let maxNum = this.formData.relationList.length
      if (maxNum < 1) {
        return callback(new Error('请选择至少一个商品（非设置成赠品）'))
      }
      return callback()
    }
    return {
      formRules: {
        name: [
          { required: true, message: '不能为空', trigger: 'change' },
          {max: 30, message: '不能超过30个字', trigger: 'change'}
        ],
        subTitle: [
          { required: true, message: '不能为空', trigger: 'change' },
          {max: 30, message: '不能超过30个字', trigger: 'change'}
        ],
        relationList: [
          { required: true, message: '请选择商品', trigger: 'change' },
          { validator: validPackageGoodsList, trigger: 'change' }
        ]},
      pageType: null,
      goodsLoading: false,
      pageLoading: false,
      btnLoading: false,
      tags: [],
      tempTagCheck: [],
      formData: { // 组合套餐数据
        relationList: [],
        tagList: [],
        imageList: []
      }
    }
  },
  activated() {
    this.setPageType()
  },
  async created() {
    if (this.$store.getters.cachedViews.length === 0) this.setPageType()
    await this.getTag()
  },
  mounted() {
    if(this.isEdit || this.pageType) {
      this.initDetail()
    }
  },
  computed: {
    isEdit() {
      return this.id
    }
  },
  methods: {
    videoJudge(item) {
      const arr = item.split('.')
      let picType = ['png', 'jpg', 'jpeg', 'bmp', 'gif']
      const res = picType.includes(arr[arr.length-1])
      return res
    },
    setPageType() {
      this.pageType = this.$route.query.pageType
    },
    // 标签获取
    async getTag() {
      const result = await getTagList()
      this.tags = result.data ? result.data : []
    },
    // 编辑获取
    initDetail() {
      this.request({
        url: '/bsnl-product/combo/package/'+ this.id,
        method: 'get'
      }).then(res => {
        this.formData = res.data || []
        this.tempTagCheck = res.data.tagList.map(item =>
          parseInt(item)
        )
        console.log('tempTagCheck', this.tempTagCheck)
        this.listLoading = false
      }).catch(e => {
        this.listLoading = false
      })
    },

    // 选套餐
    chooseGoodsPackage(){
      let selected = this.formData.relationList.map(item => {
        return {
          packageId: item.packageId,
          id: item.id,
          name: item.name,
          Sell: item.isSell,
          price: item.price,
          type: 1
        }
      });
      this.packageChoose({type: 'combo'}, selected).then(val => {
        let arr = []
        let mention = false
        val.map(item => {
          const sellStatus = item.Sell !== undefined ? item.Sell : 1
          if(item.type === 1) {
            arr.push({
              packageId: item.packageId,
              id: item.id,
              name: item.name,
              price: item.price,
              isSell: sellStatus,
              type: item.type
            })
          } else {
            mention = true
          }
        })
        this.formData.relationList = arr
        // this.$nextTick(() => {
        //   this.$set(this.formData, 'relationList', arr)
        // })
        if(mention) {
          this.$message({
            type: 'info',
            message: '所选套餐只能为固定套餐,已过滤不符合条件的内容'
          })
        }
      })
    },
    // 组图
    uploadImg(event) {
      const file = event.target.files[0];
      this.picFileUpload(file, (res) => {
        this.formData.imageList.push(this.replaceImgUrl(res.filePath));
      })
    },

    // 移除套餐
    del(item, index) {
      this.formData.relationList.splice(index, 1)
    },
    ImgSuccess(res, file) {
      this.$set(this.formData, 'image', this.replaceImgUrl(res.filePath))
    },
    // 标签更改
    changeTagArr() {
      this.formData.tagList = this.tempTagCheck.map(item => parseInt(item))
    },
    // 保存
    save() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false;
        }

        this.formData.userQuantity = 0
        if(this.isEdit){
          this.request({
            url: '/bsnl-product/combo/package/edit',
            method: 'post',
            data: this.formData
          }).then(() => {
            this.$message.success('保存成功');
            this.$router.back();
            this.btnLoading = false;
          }).catch(err => {
            this.$message.error('失败');
            this.btnLoading = false;
          });

        } else {
          this.request({
            url: '/bsnl-product/combo/package/add',
            method: 'post',
            data: this.formData
          }).then(() => {
            this.$message.success('保存成功');
            this.$router.back();
            this.btnLoading = false;
          }).catch(err => {
            this.$message.error('失败');
            this.btnLoading = false;
          });
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .section-header {
    margin-bottom: 32px;
    padding: 12px;
    background: #f8f8f8;
    box-sizing: border-box;
    span {
      color: #333;
      font-size: 14px;
      line-height: 12px;
      padding: 0 12px;
      border-left: 1px solid #409eff;
    }
  }
</style>
